package com.cmfi.utils;

import java.io.File;
import java.io.FileInputStream;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class PrinterUtils {
	
	private static final Logger log = LoggerFactory.getLogger(PrinterUtils.class);
	
	/**
	 * 根据文件路径打印，全路径
	 * @param filePath 文件路径
	 * @throws Exception
	 */
	public static void print(String filePath) throws Exception {
		try {
			FileInputStream input = new FileInputStream(new File(filePath));
			Doc doc = new SimpleDoc(input, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
			PrintService printService = PrintServiceLookup.lookupDefaultPrintService();// 查找默认打印机
			if (printService != null) {
				DocPrintJob job = printService.createPrintJob();
				job.print(doc, null);
				log.info("[PrinterServiceImpl][print] print success");
			} else {
				log.info("[PrinterServiceImpl][print] no printer");
			}
		} catch (Exception e) {
			log.error("[PrinterServiceImpl][print] e,", e);
		}
	}
	
	/**
	 * 根据文件路径打印，全路径
	 * @param filePath 文件路径
	 * @param fileType 文件类型，如：DocFlavor.INPUT_STREAM.PNG、DocFlavor.INPUT_STREAM.PDF等
	 * @throws Exception 异常
	 */
	public static void print(String filePath,DocFlavor.INPUT_STREAM fileType) throws Exception {
		try {
			FileInputStream input = new FileInputStream(new File(filePath));
			Doc doc = new SimpleDoc(input, fileType, null);
			PrintService printService = PrintServiceLookup.lookupDefaultPrintService();// 查找默认打印机
			if (printService != null) {
				DocPrintJob job = printService.createPrintJob();
				job.print(doc, null);
				log.info("[PrinterServiceImpl][print] print success");
			} else {
				log.info("[PrinterServiceImpl][print] no printer");
			}
		} catch (Exception e) {
			log.error("[PrinterServiceImpl][print] e,", e);
		}
	}
	
	public static void main(String[]args) {
		try {
			print("C:\\Users\\Lenovo\\Desktop\\喻总\\test.PNG", DocFlavor.INPUT_STREAM.PNG);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
